package com.xgr.wonderful.activity;


import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.google.gson.Gson;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.xgr.wonderful.activity.RegisterActivity;
import com.xgr.wonderful.activity.UploadAvatarActivity;
import com.xgr.wonderful.activity.base.BaseActivity;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.SettingUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.R;

public class RegisterActivity extends BaseActivity {

	private TextView usernameTv;
	private Button registerBtn;
	private ActionBar mActionBar ;
	
	private HttpProxy httpProxy ;
	
	private User mUser = null ;

	@Override
	protected void onCreate(Bundle bundle) {
		// TODO Auto-generated method stub
		super.onCreate(bundle);
		setContentView(R.layout.activity_register);
		
		mActionBar = (ActionBar)findViewById(R.id.actionbar_register) ;
		registerBtn = (Button) findViewById(R.id.register_completeBtn);
		usernameTv = (TextView) findViewById(R.id.register_usernameTv);
		
		mActionBar.setTitle("注册") ;
		mActionBar.setDisplayHomeAsUpEnabled(true) ;
		mActionBar.setHomeAction(new Action() {
			@Override
			public void performAction(View view) {
				finish();
			}
			@Override
			public int getDrawable() {
				// TODO Auto-generated method stub
				return R.drawable.weix_logo_blank;
			}
		});
		registerBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String username = usernameTv.getText().toString().trim();// 去空格
				// 查看用户名是否满足要求
				if (TextUtils.isEmpty(username) || username.length() < 3
						|| username.length() > 32) {
					ToastFactory.getToast(mContext, "用户名不满足要求").show() ;
					return;
				}
				String deviceid = SettingUtils.getDeviceId(mContext);
				registerWeiX (username, deviceid) ; //测试
			}
		});
	}
	/**
	 * 注册weix 
	 * @param username
	 * @param deviceid
	 */
	protected void registerWeiX(String username, String deviceid) {
		User user = new User(username, deviceid ) ;
		String jsonUser = new Gson().toJson(user) ;
		httpProxy = new HttpProxy() ;
		
		httpProxy.registerUser(jsonUser, new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
					ToastFactory.getToast(mContext, "WeiX注册成功").show() ;
					mUser = new Gson().fromJson(result, User.class) ;
					if (mUser != null && mUser.getUsername()!= null){
						//此处 应该保存一次用户数据 
						LocalUserUtils.getInstance().saveLocalUser(mContext, mUser) ;
						String userid = String.valueOf(mUser.getID()) ;
						registerEM (userid ,userid) ; 
					}
				}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
					cancelProgressDialog() ;
					ToastFactory.getToast(mContext, "用户名已经重要或禁止了手机识别码（这个并没有任何安全上的危险）的读取").show() ;
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
				showProgressDialog("正在注册...", false) ;
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				cancelProgressDialog();
				//失败：{"status":0,"info":”参数错误”/“用户名已存在或该设备已注册”}
				ToastFactory.getToast(mContext,"请查看您的网络").show() ;
			}
		}) ;
		
	}
	/**
	 * 注册EMChat 
	 * @param userid
	 * @param pwd
	 */
	protected void registerEM(String  userid, String  pwd) {
		CreateEmAccountTask task = new CreateEmAccountTask() ;
		task.execute(userid, pwd ) ;
	}
	
	private class CreateEmAccountTask extends AsyncTask<String , Void, String >{
		@Override
		protected void onPostExecute(String result) {
			//注册完成后的工作
			LogUtils.i(TAG, "registerEm result:"+result) ;
			cancelProgressDialog() ;
			LogUtils.i(TAG, "聊天服务器注册成功" ) ;
			redictToActivity(mContext, UploadAvatarActivity.class, null);
			super.onPostExecute(result);
		}
		@Override
		protected String doInBackground(String... params) {
			String userid = params [0] ;
			String pwd = params[1] ;
			try {
				EMChatManager.getInstance().createAccountOnServer(userid, pwd) ;
			} catch (Exception e) {
				e.printStackTrace() ;
			}
			return userid;
		}
		
	}


}
